package com.xxgc.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxgc.springboot.entity.TaskInfo;
import com.xxgc.springboot.mapper.TaskInfoMapper;
import com.xxgc.springboot.service.ITaskInfoService;
import com.xxgc.springboot.util.QuartzUtil;
import org.quartz.Job;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 定时任务表 服务实现类
 * </p>
 *
 * @author Mr.Abel
 * @since 2022-09-20
 */
@Service
public class TaskInfoServiceImpl extends ServiceImpl<TaskInfoMapper, TaskInfo> implements ITaskInfoService {
    @Autowired
    private TaskInfoMapper tim;

    //事务
    @Override
    @Transactional(rollbackFor = {ClassNotFoundException.class, SchedulerException.class})
    public int saveOrTask(TaskInfo taskInfo) throws ClassNotFoundException, SchedulerException {
        //1、写入到数据库
        tim.insert(taskInfo);
        //2、根据传递参数配置Quartz
        //getDetailName 完整类名加包名
        QuartzUtil.addJob(
                taskInfo.getDetailName(),
                taskInfo.getDetailGroup(),
                taskInfo.getTriggerName(),
                taskInfo.getTriggerGroup(),
                taskInfo.getCron(),
                (Class<? extends Job>) Class.forName(taskInfo.getDetailJob()));
        return 1;
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public int removeTaskById(Integer id) throws SchedulerException {
        //从数据库查询出任务的信息
        TaskInfo ti = tim.selectById(id);
        if(ti == null){
            return 2;
        }
        //工具类删除任务
        QuartzUtil.deleteJob(
                ti.getDetailName(),
                ti.getDetailGroup(),
                ti.getTriggerName(),
                ti.getTriggerGroup());
        //数据库删除任务
        tim.deleteById(id);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public int suspendTaskById(Integer id) throws SchedulerException {
        //从数据库查询出任务的信息
        TaskInfo ti = tim.selectById(id);
        if(ti == null){
            return 2;
        }
        //暂停
        QuartzUtil.suspendJob(ti.getTriggerName(),ti.getTriggerGroup());
        ti.setJobFlag(2);
        tim.updateById(ti);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = SchedulerException.class)
    public int runTaskById(Integer id) throws SchedulerException {
        //从数据库查询出任务的信息
        TaskInfo ti = tim.selectById(id);
        if(ti == null){
            return 2;
        }
        //暂停
        QuartzUtil.runJob(ti.getTriggerName(),ti.getTriggerGroup());
        ti.setJobFlag(1);
        tim.updateById(ti);
        return 1;
    }
}
